package top.xiaoazi.futureletterserver.module.letter.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.xiaoazi.futureletterserver.module.letter.service.LetterService;
import top.xiaoazi.futureletterserver.module.letter.vo.LetterSentVO;
import top.xiaoazi.futureletterserver.utils.TimeUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 信件管理工具类, 用于给用户发送邮箱等等
 */

@Slf4j
@Component
public class LetterPushUtils  {
    @Autowired
    private LetterService letterService;

    private Set<LetterSentVO> data = new HashSet<>();

    private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2); // 根据实际情况调整线程池大小

    /**
     * 发送信件
     */
    public void push() {
        log.info("执行了发送信件, LetterPushUtils -> push()");
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();

        // 获取当天的0点时间
        LocalDateTime startOfDay = currentDate.atStartOfDay();
        long startTimestamp = startOfDay.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();

        // 获取当天的23:59:59时间
        LocalDateTime endOfDay = currentDate.atTime(LocalTime.MAX);
        long endTimestamp = endOfDay.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();

        // 获取今天要发送的信件数据
        this.data.addAll(letterService.getAwaitSendLetterOnToday(startTimestamp, endTimestamp));

        // 依次将今天要发送的信件放入定时器中，进行定时发送
        for (LetterSentVO item : this.data) {
            // 获取等待执行的时间
            long curTime = TimeUtils.currentTimeMillis();
            long sendTime = item.getSendTime().getTime();
            long delayTime = sendTime - curTime;
            // 立刻要发送的情况
            if (delayTime < 0L) {
                delayTime = 0L;
            }
            LetterTask letterTask = new LetterTask();
            letterTask.setLetter(item);
            // 设置要执行的任务，延迟执行时间，时间单位
            executorService.schedule(letterTask, delayTime, TimeUnit.MILLISECONDS);
        }
        this.data = new HashSet<>();
    }
}
